package red.mlz.consoleconsumer.controller.excel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import red.mlz.common.entity.user.User;
import red.mlz.common.utils.BaseUtils;
import red.mlz.common.utils.Response;
import red.mlz.consoleconsumer.annotations.VerifiedUser;
import red.mlz.consoleconsumer.feign.excel.ExcelFeign;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@Slf4j
public class ExcelController {

    @Autowired
    private ExcelFeign excelFeign;

    @RequestMapping("/excel/upload")
    public Response upload(@VerifiedUser User loginUser,
                           @RequestPart(name = "file") MultipartFile file,
                           @RequestParam(value = "headerRow", defaultValue = "0") int headerRow) {

        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }

        return new Response(1001,excelFeign.upload(file, headerRow));
    }

    @RequestMapping("/categories/export")
    public void exportCategories(HttpServletResponse response) {
        try {
            ResponseEntity<byte[]> responseEntity = excelFeign.exportCategories();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=categories.xlsx");
                response.getOutputStream().write(responseEntity.getBody());
            } else {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.setContentType("application/json");
                response.getWriter().write(new String(responseEntity.getBody()));
            }
        } catch (Exception e) {
            handleExportError(response, e);
        }
    }

    private void handleExportError(HttpServletResponse response, Exception e) {
        try {
            if (!response.isCommitted()) {
                response.reset();
                response.setContentType("application/json; charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                String json = String.format(
                        "{\"code\":500,\"message\":\"%s\"}",
                        e.getMessage()
                );
                response.getWriter().write(json);
            } else {
                log.error("无法返回错误信息，响应已提交");
            }
        } catch (IOException ex) {
            log.error("处理导出异常失败", ex);
        }
    }

}
